<template>
  <div class="search">
    <h1>车辆管理</h1>
    <hr style="border: 1px solid rgb(240, 240, 240)" />
    <span>车牌号</span>
    <el-input
      v-model="region_name"
      style="width: 200px; margin-right: 10%"
      placeholder="请输入车牌号"
    />
    <el-button type="primary" @click="searchVehicle">查询</el-button>
    <el-button type="default" @click="resetForm">重置</el-button>
  </div>
  <div class="page">
    <div class="page-header">
      <div class="page-header-left">
        <span>车辆列表</span>
      </div>
      <div class="page-header-right">
        <el-button
          type="primary"
          style="margin-top: 1rem"
          @click="to('car/newCar')"
          >+&nbsp;新建
        </el-button>
        <el-button
          type="default"
          style="margin-top: 1rem; margin-right: 3rem"
          @click="deleteDialog = true"
          >批量删除</el-button
        >
        <el-dialog v-model="deleteDialog" title="警告" width="500" align-center>
          <span>是否删除选中的信息，该操作不可撤回！</span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="deleteDialog = false">取消</el-button>
              <el-button type="primary" @click="deleteByIds"> 确认 </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column prop="carNo" label="车牌号" />
      <el-table-column prop="brand" label="车辆品牌" />
      <el-table-column prop="size" label="车辆型号" />
      <el-table-column prop="color" label="车身颜色" />
      <el-table-column prop="owner" label="持有人" />
      <el-table-column prop="notes" label="备注" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="openDetailDialog(row.id)" type="text"
            >查看</el-button
          >
          <el-button @click="deleteVehicle(row.id)" type="text">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        style="margin-bottom: 2rem"
        background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
import to from "@/utils/to.js";
import router from "@/router";
import { ElMessage } from "element-plus";

const loading = ref(false);
const deleteDialog = ref(false);
const selectRows = ref([]);

// 初始化数据和状态
const pageSizeOptions = [5, 10, 20];
const pageNum = ref(1);
const pageSize = ref(pageSizeOptions[0]);
const position_status = ref("");
const region_name = ref("");
const options = [
  { value: "", label: "全部" },
  { value: "审核中", label: "审核中" },
  { value: "审核通过", label: "审核通过" },
  { value: "审核不通过", label: "审核不通过" },
];

const tableData = ref([]);
const totalCount = ref(0);

// 表单数据
const form = reactive({
  id: "",
  car_no: "",
  brand: "",
  size: "",
  color: "",
  images: "",
  owner: "",
  notes: "",
});

// 发送查询请求，获取车位数据
const searchVehicle = async () => {
  try {
    loading.value = true;
    const response = await axios.get(
      "http://localhost:8080/vehicleCar/list",
      {
        headers: {
          Authorization: localStorage.getItem("token"),
        },
        params: {
          pageNum: pageNum.value,
          pageSize: pageSize.value,
          carNo: region_name.value, // 根据车牌号查询
          status: position_status.value, // 根据绑定状态查询
        },
      }
    );
    tableData.value = response.data.records;
    totalCount.value = response.data.total;
    loading.value = false;
  } catch (error) {
    console.error("查询车辆失败:", error);
  }
};

// 打开车位详情对话框
const openDetailDialog = async (id) => {
  try {
    router.push({ path: "/backend/car/newCar", query: { id: id } });
  } catch (error) {
    console.error("获取车辆详情失败:", error);
  }
};

// 重置表单
const resetForm = () => {
  // 清空查询车牌号和绑定状态
  region_name.value = "";
  position_status.value = "";
  // 查询所有车辆
  searchVehicle();
};

const handleSelectionChange = (selectedRows) => {
  selectRows.value = selectedRows;
};

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  searchVehicle();
};

// 处理当前页变化
const handleCurrentChange = (newPage) => {
  pageNum.value = newPage;
  searchVehicle();
};

// 页面加载时查询车辆数据
onMounted(() => {
  searchVehicle();
});

const deleteByIds = () => {
  if (selectRows.value.length === 0) {
    ElMessage({
      message: "请选择要删除的信息",
      type: "warning",
    });
    deleteDialog.value = false;
    return;
  }

  const config = {
    url: "http://localhost:8080/vehicleCar/deleteByIds",
    method: "DELETE",
    headers: {
      Authorization: localStorage.getItem("token"),
    },
    data: selectRows.value.map((item) => item.id),
  };

  const response = axios(config);
  response
    .then((data) => {
      if (data.data.code === 1) {
        ElMessage({
          message: "删除成功",
          type: "success",
        });
        setTimeout(() => {
          searchVehicle();
        }, 2000);
      }
    })
    .catch((error) => {
      console.log(error);
    });
  deleteDialog.value = false;
};
</script>

<style scoped>
.search {
  background-color: white;
  padding-bottom: 2rem;
  height: auto;
  margin-top: 2rem;
}

h1 {
  font-size: 2rem;
  font-weight: 600;
  padding: 2rem 0 10px 4rem;
}

span {
  display: inline-block;
  font-size: 15px;
  margin-top: 2rem;
  margin-left: 3rem;
  margin-right: 1rem;
  height: 24px;
}

.page {
  background-color: white;
  height: auto;
  margin-top: 2rem;
  margin-bottom: 2rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  display: flex;
  margin-top: 2rem;
  justify-content: center;
}
</style>
